package com.xiaoxiang.auth.config;

import com.xiaoxiang.auth.constant.AuthConstant;
import com.xiaoxiang.auth.dto.RolePermissionDo;
import com.xiaoxiang.auth.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *
 * 角色对应权限点缓存
 * @author: haha
 * @date: 2022/2/15 11:13
 */
@Component
@Slf4j
public class PermissionCache {

    @Resource
    private RedisTemplate<String, List<RolePermissionDo>> redisTemplate;

    @Resource
    private PermissionService permissionService;

    @Value("${auth.cache.expire}")
    private Long expire;

    @PostConstruct
    private void initCache() {
        List<RolePermissionDo> roleMenuDOList = permissionService.queryAllByRole();
        log.debug("角色对应权限点读取成功，{}", roleMenuDOList);
        redisTemplate.opsForValue().set(AuthConstant.ROLE_PERMISSION_KEY, roleMenuDOList,
                expire, TimeUnit.SECONDS);
    }

    public void resetCache() {
        initCache();
    }

    public void resetCache(List<RolePermissionDo> roleMenuDOList) {
        log.debug("角色对应权限点读取成功，{}", roleMenuDOList);
        redisTemplate.opsForValue().set(AuthConstant.ROLE_PERMISSION_KEY, roleMenuDOList,
                expire, TimeUnit.SECONDS);
    }

    public List<RolePermissionDo> getCache() {
        List<RolePermissionDo> rolePermissionDoList = redisTemplate.opsForValue()
                .get(AuthConstant.ROLE_PERMISSION_KEY);
        if (CollectionUtils.isEmpty(rolePermissionDoList)) {
            rolePermissionDoList = permissionService.queryAllByRole();
            this.resetCache(rolePermissionDoList);
        }
        return rolePermissionDoList;
    }

}
